import 'dart:async';

import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/login/personinformation/personinformation_one.dart';
import 'package:fate_blind_box/ui/login/personinformation/personinformation_three.dart';
import 'package:fate_blind_box/ui/login/personinformation/personinformation_two.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import '../../../network/Api.dart';
import '../../../utils/provider.dart';
import '../../../utils/snack_bar.dart';

class PersonInformationZeroPageWidget extends StatefulWidget {
  final String type;
  final String? aaa;

  const PersonInformationZeroPageWidget(this.type, {Key? key, this.aaa})
      : super(key: key);

  @override
  State<PersonInformationZeroPageWidget> createState() =>
      _PersonInformationZeroPageWidgetState();
}

class _PersonInformationZeroPageWidgetState
    extends State<PersonInformationZeroPageWidget> {
  late Size _screen;
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  final _passController = TextEditingController();
  final _surePassController = TextEditingController();
  bool _isSee = true;
  bool _isSeeAgain = true;

  @override
  Widget build(BuildContext context) {
    _screen = MediaQuery.of(context).size;
    return AppWidget.navTitleBar(
      title: '绑定手机号',
      childWidget: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Container(
            decoration: ShapeDecoration(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15)),
                color: Colors.white),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const SizedBox(
                  height: 50,
                ),
                Container(
                  height: 45,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  margin:
                      const EdgeInsets.symmetric(vertical: 12, horizontal: 41),
                  decoration: ShapeDecoration(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(5)),
                      color: const Color(0xFFF6F8FA)),
                  alignment: Alignment.centerLeft,
                  child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    maxLines: 1,
                    decoration: InputDecoration(
                        hintText: "请输入手机号",
                        hintStyle: const TextStyle(fontSize: 12),
                        suffixIcon: GestureDetector(
                          onTap: () {
                            setState(() {
                              _phoneController.text = '';
                            });
                          },
                          child: const Icon(
                            Icons.cancel,
                            size: 20,
                            color: Color(0xFFCCCCCC),
                          ),
                        ),
                        border: InputBorder.none,
                        counterText: ''),
                    style:
                        const TextStyle(fontSize: 12, color: Color(0xFF3A3A3A)),
                  ),
                ),
                Container(
                    height: 45,
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    margin: const EdgeInsets.symmetric(
                        vertical: 12, horizontal: 41),
                    decoration: ShapeDecoration(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5)),
                        color: const Color(0xFFF6F8FA)),
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: _codeController,
                            keyboardType: TextInputType.phone,
                            maxLength: 11,
                            maxLines: 1,
                            decoration: const InputDecoration(
                                hintText: "请输入验证码",
                                hintStyle: TextStyle(fontSize: 12),
                                border: InputBorder.none,
                                counterText: ''),
                            style: const TextStyle(
                                fontSize: 12, color: Color(0xFF3A3A3A)),
                          ),
                        ),
                        Container(
                            width: 102,
                            height: 32,
                            decoration: BoxDecoration(
                                // border: Border.all(color: ThemeColor.appColor),
                                borderRadius: BorderRadius.circular(15),
                                color: ThemeColor.appColor),
                            alignment: Alignment.center,
                            child: GestureDetector(
                              onTap: () {
                                _sendVerifyCode();
                              },
                              child: Text(
                                _curTime > 0 ? "$_curTime秒后重新获取" : "获取验证码",
                                style: const TextStyle(
                                    color: Colors.white, fontSize: 12),
                              ),
                            ))
                      ],
                    )),
                Container(
                  height: 45,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  margin:
                      const EdgeInsets.symmetric(vertical: 12, horizontal: 41),
                  decoration: ShapeDecoration(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(5)),
                      color: const Color(0xFFF6F8FA)),
                  alignment: Alignment.centerLeft,
                  child: TextField(
                    controller: _passController,
                    maxLength: 18,
                    maxLines: 1,
                    obscureText: _isSee,
                    decoration: InputDecoration(
                        hintText: "请输入6-18位密码（数字/字母/字符)",
                        hintStyle: const TextStyle(fontSize: 12),
                        suffixIcon: SizedBox(
                          width: 60,
                          // color: Colors.red,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  setState(() {
                                    _passController.text = '';
                                  });
                                },
                                child: const Icon(
                                  Icons.cancel,
                                  size: 20,
                                  color: Color(0xFFCCCCCC),
                                ),
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                              GestureDetector(
                                onTap: () {
                                  setState(() {
                                    _isSee = !_isSee;
                                  });
                                },
                                child: Icon(
                                  _isSee
                                      ? Icons.visibility_off
                                      : Icons.visibility,
                                  size: 22,
                                  color: const Color(0xFFCCCCCC),
                                ),
                              )
                            ],
                          ),
                        ),
                        border: InputBorder.none,
                        counterText: ''),
                    style:
                        const TextStyle(fontSize: 12, color: Color(0xFF3A3A3A)),
                  ),
                ),
                Container(
                  height: 45,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  margin:
                      const EdgeInsets.symmetric(vertical: 12, horizontal: 41),
                  decoration: ShapeDecoration(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(5)),
                      color: const Color(0xFFF6F8FA)),
                  alignment: Alignment.centerLeft,
                  child: TextField(
                    controller: _surePassController,
                    maxLength: 18,
                    maxLines: 1,
                    obscureText: _isSeeAgain,
                    decoration: InputDecoration(
                        hintText: "请再次输入密码",
                        hintStyle: const TextStyle(fontSize: 12),
                        suffixIcon: SizedBox(
                          width: 60,
                          // color: Colors.red,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  setState(() {
                                    _surePassController.text = '';
                                  });
                                },
                                child: const Icon(
                                  Icons.cancel,
                                  size: 20,
                                  color: Color(0xFFCCCCCC),
                                ),
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                              GestureDetector(
                                onTap: () {
                                  setState(() {
                                    _isSeeAgain = !_isSeeAgain;
                                  });
                                },
                                child: Icon(
                                  _isSeeAgain
                                      ? Icons.visibility_off
                                      : Icons.visibility,
                                  size: 22,
                                  color: const Color(0xFFCCCCCC),
                                ),
                              )
                            ],
                          ),
                        ),
                        border: InputBorder.none,
                        counterText: ''),
                    style:
                        const TextStyle(fontSize: 12, color: Color(0xFF3A3A3A)),
                  ),
                ),
                const SizedBox(
                  height: 50,
                ),
                Container(
                    margin: const EdgeInsets.symmetric(horizontal: 41),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: GestureDetector(
                            onTap: () {
                              _submit();
                            },
                            child: Container(
                              height: 45,
                              decoration: BoxDecoration(
                                  color: ThemeColor.appColor,
                                  borderRadius: BorderRadius.circular(24)),
                              alignment: Alignment.center,
                              child: const Text(
                                "确定",
                                style: TextStyle(
                                    color: Colors.white, fontSize: 18),
                              ),
                            ),
                          ),
                        ),
                      ],
                    )),
                const SizedBox(
                  height: 14,
                ),
                Container(
                  margin:
                      const EdgeInsets.only(left: 14, right: 14, bottom: 20),
                  child: Text.rich(TextSpan(children: [
                    const TextSpan(
                        text: "本操作将会重置您的登陆密码，",
                        style:
                            TextStyle(color: Color(0xFFCECECE), fontSize: 10)),
                    TextSpan(
                      text: "请牢记您的新密码",
                      style:
                          TextStyle(color: ThemeColor.appColor, fontSize: 10),
                      recognizer: TapGestureRecognizer()..onTap = () {},
                    ),
                  ])),
                ),
                const SizedBox(
                  height: 20,
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Timer? _timer;
  int _curTime = 0;

  _startCountdownTimer() {
    _curTime = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _curTime--;
      });
      if (_curTime <= 0) {
        _timer?.cancel();
      }
    });
  }

  bool _verify(bool sendCode) {
    if (_phoneController.text.isEmpty) {
      toast("请输入手机号");
      return false;
    }
    if (sendCode) {
      return true;
    }
    if (_codeController.text.isEmpty) {
      toast("请输入验证码");
      return false;
    }
    if (_passController.text.isEmpty) {
      toast("请输入密码");
      return false;
    }
    if (_surePassController.text.isEmpty) {
      toast("请再次输入密码");
      return false;
    }
    return true;
  }

  String? _smsSig;

  _sendVerifyCode() {
    if (!_verify(true)) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance().loginSendCode(_phoneController.text);
      if (res['code'] == 0) {
        if (res['data'] != null && res['data']['sig'] != null) {
          _smsSig = res['data']['sig'];
          _startCountdownTimer();
        } else {
          toast("验证码发送失败");
        }
      } else {
        toast(res['msg']);
      }
    });
  }

  _submit() {
    if (!_verify(false)) {
      return;
    }
    if (_smsSig == null || _smsSig!.isEmpty) {
      toast("请先获取验证码");
      return;
    }
    loading(() async {
      final res = await Api.getInstance().perfectInformationBindingPhoneNumber(
        _phoneController.text,
        _codeController.text,
        _smsSig!,
        _passController.text,
        _surePassController.text,
      );
      if (res['code'] == 0) {
        toast(res['msg']);
        if (widget.type == '微信') {
          Navigate.toPage(const PersonInformationPage());
        } else {
          _getUserInfo();
        }
      } else {
        toast(res['msg']);
      }
    });
  }

  _getUserInfo() {
    loading(() async {
      final res = await Api.getInstance().getMemberInfo(Provider.memberId);
      print('xxxxxx $res');
      if (res['code'] == 0) {
        final data = res['data'];
        if (data['bornDate'].toString() == 'null' ||
            data['bornDate'].toString().isEmpty) {
          Navigate.toPage(const PersonInformationPage());
        } else if (data['height'].toString() == 'null' ||
            data['height'].toString().isEmpty) {
          Navigate.toPage(const PersonInformationTwoPage());
        } else if (data['mcs']['ageStart'].toString() == 'null' ||
            data['ageStart'].toString().isEmpty) {
          Navigate.toPage(const PersonInformationThreePage());
        } else {
          Navigate.toMain();
        }
      } else {
        ThemeSnackBar.show(context, res['msg']);
      }
    });
  }
}
